<?php
namespace Common\Lib;

use \Think\Crypt;

/**
 * 微博上传回调类
 * @author Baiyu
 */
class SessionLib {
	
	public	static $sessionDbItem;
	private	static $cryptKey;
	
	//初始化SESSION入口
	public static function init($type) {
		try {
			return call_user_func(array('self', '_init' . ucfirst(strtolower($type))));
		} catch (\Exception $e) {
			return FALSE;
		}
	}
	
	//APP的SESSION机制
	private function _initApp() {
		
		//配置加解密模式
		C('DATA_CRYPT_TYPE', 'Think');
		self::$cryptKey = C('SESSION_CRYPTKEY') ?: 'SESSIONCRYPTKEY';
		
		//session配置
		session(array(
				'name' => 'NEWSESSID',
				'expire' => 2592000,
				'type' => 'dbsess',
		));
		
		//从request header中取出NEWSESSID并解密得到session_id和
		$session_id = '';
		$last_access = 0;
		if (!empty($_SERVER['HTTP_NEWSESSID'])) {
			//解密
			$session_str = Crypt::decrypt($_SERVER['HTTP_NEWSESSID'], self::$cryptKey);
			list($session_id, $last_access) = explode("\t", $session_str);
		
			//设置session_id
			if ($session_id && $last_access) {
				session_id($session_id);
			}
		}
		
		//request header中没有带NEWSESSID或NEWSESSID不合法时创建新session_id
		if (!$session_id){
			session_regenerate_id();
		}
		
		//session初始化
		session('[start]');
				
		//防止非法窃取NEWSESSID
		if (isset(self::$sessionDbItem['last_access']) && self::$sessionDbItem['last_access'] - $last_access > 86400) {
			session(null);
			session_destroy();
			session_start();
			session_regenerate_id();
		}
		
		//生成NEWSESSID并通过response header发送
		$newsessid = Crypt::encrypt(session_id()."\t".NOW_TIME, self::$cryptKey);
		header('NEWSESSID: ' . $newsessid);
		
		return $newsessid;
	}
}